<?php
/**
 *
 * @authors  Ysg (y.shi.guo@gmail.com)
 * @website  http://ysg.bonza.cn
 * @date     2017-07-24 11:43:02
 */

header("Content-type:text/html;charset:utf8;");

date_default_timezone_set('PRC');

$servername = 'localhost';//127.0.0.1
$dbname ='demo';
$dbuser = 'root';
$dbpass = 'root';
$dbport = 3306;
$dbtype = 'mysql';



//面向过程的写法
/*$conn = mysqli_connect($servername,$dbuser,$dbpass,$dbname,$dbport);

if (!$conn) {
	echo "数据库连接失败". mysqli_connect_error();
}else{
	echo "数据库连接成功";
}
echo "<br />";*/
//面向对象的写法
/*$conn = new mysqli($servername,$dbuser,$dbpass,$dbname,$dbport);
if ($conn->connect_error) {
	echo "连接失败".$conn->connect_error;
}else{
	echo '数据库连接成功';
}
echo "<br />";*/
// echo $conn->character_set_name();
// $conn->select_db($dbname);

//使用PDO连接数据库
$dsn = "$dbtype:host=$servername:$dbport;dbname=$dbname";
try {
	$conn = new PDO($dsn,$dbuser,$dbpass);
	// echo "数据库连接成功";
} catch (PDOException $e) {
	echo $e->getMessage();
}
// echo $conn->getAttribute(PDO::ATTR_AUTOCOMMIT);die;
// echo $conn->getAttribute(PDO::ATTR_CASE);die;
// echo $conn->getAttribute(PDO::ATTR_CLIENT_VERSION);die;
// echo $conn->getAttribute(PDO::ATTR_DRIVER_NAME);die;
// $sql = "INSERT INTO users (`name`,`age`,`sex`) VALUES (:name,:age,:sex)";
// $result = mysqli_query($conn,$sql);

// $arr = mysqli_fetch_all($result);
// print_r($arr);

/*while ($rows = mysqli_fetch_assoc($result)) {
	echo "姓名：".$rows['name'].";年龄：".$rows['age']."<br/>";
}*/
// $stmt = $conn->prepare($sql);
// $stmt->bindParam(':name',$name);
// $stmt->bindParam(':age',$age);
// $stmt->bindParam(':sex',$sex);
// var_dump($stmt);die;
// $name = 'wangwu';
// $age = 18;
// $sex = 2;
// $stmt->execute();
// echo $conn->lastInsertId();

// $result  = $stmt->get_result();
// $rows  = $result->fetch_all(MYSQLI_ASSOC);
// print_r($rows);die;
// while ($rows = $result->fetch_assoc()) {
// 	print_r($rows);
// }

$sql = "SELECT * FROM users";
$stmt = $conn->query($sql);
foreach ($stmt as $value) {
	echo $value['age']."<br/>";
	# code...
}
















